package com.pangu.export.controller;

import com.pangu.export.dto.TableColumnDto;
import com.pangu.export.entity.TableColumn;
import com.pangu.export.service.ExcelService;
import com.pangu.export.service.TableColumnService;
import com.pangu.export.utils.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by etfox on 2019/10/25 23:44
 */
@RestController
@RequestMapping("exportExcel")
@Api("数据库导出Excel")
@CrossOrigin
@Slf4j
public class ExportController {

    @Resource
    private TableColumnService tableColumnService;

    @Resource
    private ExcelService excelService;

    @PostMapping("printAll")
    @ApiOperation(value = "导出表结构")
    public ResponseEntity<Object> printAll(@RequestBody TableColumnDto tableColumnDto) {
        try {
            List<TableColumn> tableColumns = tableColumnService.getAllTableColumn(tableColumnDto.getDataSourceName(),
                    tableColumnDto.getTableName());
            Map<String, List<TableColumn>> map = MapUtil.dealTableColumn(tableColumns);
            excelService.createTableColumnExcel(map, tableColumnDto);
        } catch (Exception e) {
            log.info("导出表结构出现异常: {}", e);
            return new ResponseEntity<>(e.getLocalizedMessage(), HttpStatus.ACCEPTED);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
